<?php

/**
 * SettingForm class.
 * SettingForm keeps the editable page settings.
 */
class SettingForm extends CFormModel{
	// each attribute must be declared as private member variable with prefix _
	private $_indexPageId;
	private $_defaultLayoutId;
	
	/**
	 * (non-PHPdoc)
	 * @see framework/base/CModel::rules()
	 */
	public function rules()
	{
		return array(
			array('indexPageId, defaultLayoutId', 'required'),
			array('indexPageId, defaultLayoutId', 'numerical', 'integerOnly'=>true),
		);
	}

	/**
	 * (non-PHPdoc)
	 * @see framework/base/CModel::attributeLabels()
	 */
	public function attributeLabels(){
		return array(
			'indexPageId'=>Yii::t('back', 'Index Page'),
			'defaultLayoutId'=>Yii::t('back', 'Default Layout'),
		);
	}
	
	/**
	 * Magic getter method
	 * checks first, if name is a safe attribute.
	 * If yes, the attribute is loaded from the settings extension.
	 * @param string $name
	 */
	public function __get($name){
		$varName = '_'.$name;
		if($this->isAttributeSafe($name)){
			if(!isset($this->$varName)){
				return $this->$varName = Yii::app()->settings->get('page', $name);
			} else {
				return $this->$varName;
			}
		}
		return parent::__get($name);
	}
	
	/**
	 * Magic setter method
	 * @param string $name
	 * @param mixed $value
	 */
	public function __set($name, $value){
		$varName = '_'.$name;
		if($this->isAttributeSafe($name)){
			$this->$varName = $value;
			return;
		}
		parent::__set($name, $value);
	}
	
	/**
	 * Saves all attributes to the settings extension.
	 */
	public function save(){
		if($this->validate()){
			foreach($this->getSafeAttributeNames() as $name){
				$varName = '_'.$name;
				Yii::app()->settings->set('page', $name, $this->$varName);
			}
			return true;
		}
		return false;
	}
}
